<?php

namespace Admin\Controller;
use Org\Util\String;
class AuserController extends BaseController
{
	public function index(){
		$list=D('Admin')->relation(true)->select();
		$this->assign('list',$list);
		$this->display();
	}
	
	public function add(){
		if(IS_POST){
			$uModel   = D("Admin");
			if(!$uModel->create(I("post."))) $this->error($uModel->getError());
			$salt = String::randString(6,1);
			$uModel->adm_password= password_encrypt(I("post.adm_password",""),$salt);
			$uModel->salt = $salt;
			$uid = $uModel->add();
			M("RoleUser","rbac_")->add(array("role_id"=>I("post.role",0,"intval"),"user_id"=>$uid));
		    $this->success("新增管理员成功",U("auser/index"));
		    exit();
		}
		$this->assign("role",$this->_getRole());
		$this->display();
	}
	
	public function edit(){
		$id=I("get.id",0,"intval");
		if($id==1) $this->error("超级管理员不能编辑");
		if(IS_POST){
			$id=I("post.id",0,"intval");
			$map['adm_name']=I("post.adm_name","","trim");
			$uModel=D("Admin");
			// 验证唯一性
			$uid=$uModel->getFieldByAdmName($map['adm_name'],"id");
			
			if($uid&&$uid!=$id){
				$this->error("用户名称已经使用");
			}
			$map['status']=I("post.status",0,"intval");
			$uModel->where(array('id'=>$id))->save($map);
			M("RoleUser","rbac_")->where(array('user_id'=>$id
			))->save(array("role_id"=>I("post.role",0,"intval")));
			
			$this->success('编辑成功');
			
			return false;
		}
		
		$user=D("Admin")->relation(true)->find($id);
		$this->assign("user",$user);
		$this->assign("role",$this->_getRole());
		$this->display();
	}
	
	public function del(){
		$uid = I("get.id",0,"intval");
		$uModel = D("Admin");
		$uModel->startTrans();
		$bool1 = $uModel->delete($uid);
		$bool2 = M("RoleUser","rbac_")->where(array('user_id'=>$uid))->delete();
		if($bool1&&$bool2){
			$uModel->commit();
			$this->success("删除成功");
		}else{
			$uModel->rollback();
			$this->error("删除失败");
		}
	}
	
	public function tostatus(){
		$uid = I("get.id",0,"intval");
		$status = I("get.status",0,"intval");
		$status = ($status)?0:1;
		D("Admin")->where(array('id'=>$uid))->save(array('status'=>$status));
		$this->success("ok");
	}
	
	private function _getRole(){
		return D("Role")->where(array("status"=>1
		))->select();
	}
}

?>